package uw10.app.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.util.Log;

import uw10.app.data.sources.RecentPrioritySource;

public class ClientServerManager implements RecentPrioritySource
{
	private long lastTime;
	
	private String pingServer;
	private int pingPort;
	
	public synchronized void setupPing(String server, int port)
	{
		pingServer = server;
		pingPort = port;
	}
	
	public synchronized int getRecentPriority()
	{
		Log.w("Get Recent Priority", pingServer + " : " + pingPort);
		int priority = -1;

		Socket sock = null;
		try
		{
			sock = new Socket(pingServer, pingPort);

			OutputStream out = sock.getOutputStream();
			
			long t = lastTime;
			for (int i = 0; i < 4; i++)
			{
				out.write((int) t & 255);
				t = t >> 8;
			}
			
			InputStream in = sock.getInputStream();
			
			priority = in.read();
			
			lastTime = System.currentTimeMillis() / 1000;
		}
		catch (Exception e) { }
		
		try
		{
			sock.close();
		} catch (Exception e) { }
		
		Log.w("Recent Priority!", String.valueOf(priority));
		
		return priority;
	}
}
